package com.suixun.service.credits.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suixun.dao.JfArticleGoodsArchivesMapper;
import com.suixun.dao.JfGoodsArchivesMapper;
import com.suixun.dao.JfPutAreaMapper;
import com.suixun.entity.JfArticleGoodsArchives;
import com.suixun.entity.JfArticleGoodsArchivesExample;
import com.suixun.entity.JfGoodsArchives;
import com.suixun.entity.JfGoodsArchivesExample;
import com.suixun.entity.JfPutArea;
import com.suixun.entity.JfPutAreaExample;
import com.suixun.entity.SysOrgnization;
import com.suixun.entity.ext.credits.ExtPutGoods;
import com.suixun.service.RegionService;
import com.suixun.service.credits.PutGoodsService;

import rop.thirdparty.org.apache.commons.lang3.StringUtils;

@Service
public class PutGoodsServiceImpl implements PutGoodsService {

	@Resource
	private JfGoodsArchivesMapper jfGoodsArchivesMapper;
	@Resource
	private JfArticleGoodsArchivesMapper jfArticleGoodsArchivesMapper;
	@Resource
	private JfPutAreaMapper jfPutAreaMapper;
	@Resource
	private RegionService regionService;
	@Resource
	private SqlSessionTemplate sqlSessionTemplate;

	@Override
	public void addArticleGoodsArchives(Integer articleId, String goodsNumbers) {

		if (StringUtils.isNotBlank(goodsNumbers)) {
			String[] goodsNumberArr = goodsNumbers.split(",");
			if (goodsNumberArr.length > 5) {
				throw new RuntimeException("商品数量超过5个");
			}
			for (String goodsNumber : goodsNumberArr) {
				addArticleGoodsArchive(articleId, goodsNumber);
			}
		}
	}

	private void addArticleGoodsArchive(Integer articleId, String goodsNumber) {
		// 判断商品是否存在
		JfGoodsArchives jfGoodsArchives = getJfGoodsArchives(goodsNumber);

		checkGoodsArchive(jfGoodsArchives, goodsNumber);

		// 判断商品是否是免费商品
		if (jfGoodsArchives.getConsumeCredit() != 0) {
			throw new RuntimeException(String.format("编号为%s的商品不是免费商品", goodsNumber));
		}

		// 新增
		addArticleGoodsArchive(articleId, jfGoodsArchives.getId());
	}

	private void checkGoodsArchive(JfGoodsArchives jfGoodsArchives, String goodsNumber) {
		if (jfGoodsArchives == null) {
			throw new RuntimeException(String.format("编号为%s的商品不存在或已禁用", goodsNumber));
		}

		// 判断商品是否已通过审核
		if (!"2".equals(String.valueOf(jfGoodsArchives.getAuditStatus()))) {
			throw new RuntimeException(String.format("编号为%s的商品审核未通过", goodsNumber));
		}

		// 判断商品是否已过期
		if (jfGoodsArchives.getEndTime() != null && jfGoodsArchives.getEndTime().compareTo(new Date()) != 1) {
			throw new RuntimeException(String.format("编号为%s的商品已过期", goodsNumber));
		}

		// 判断商品数量是否充足
		if (jfGoodsArchives.getAvailableNum() == 0) {
			throw new RuntimeException(String.format("编号为%s的商品库存不足", goodsNumber));
		}
	}

	private void addArticleGoodsArchive(Integer articleId, Integer goodsArchivesId) {
		JfArticleGoodsArchives jfArticleGoodsArchives = new JfArticleGoodsArchives();
		jfArticleGoodsArchives.setCreateTime(new Date());
		jfArticleGoodsArchives.setArticleId(articleId);
		jfArticleGoodsArchives.setGoodsArchivesId(goodsArchivesId);
		jfArticleGoodsArchivesMapper.insertSelective(jfArticleGoodsArchives);
	}

	private JfGoodsArchives getJfGoodsArchives(String goodsNumber) {
		JfGoodsArchivesExample jfGoodsArchivesExample = new JfGoodsArchivesExample();
		jfGoodsArchivesExample.createCriteria().andUuidEqualTo(goodsNumber).andStatusEqualTo((short) 1)
				.andAuditStatusEqualTo((short) 2);
		List<JfGoodsArchives> goodsArchivesList = jfGoodsArchivesMapper.selectByExample(jfGoodsArchivesExample);
		if (CollectionUtils.isEmpty(goodsArchivesList)) {
			return null;
		} else {
			return goodsArchivesList.get(0);
		}
	}

	@Override
	public void updateArticleGoodsArchives(Integer articleId, String goodsNumbers) {

		if (StringUtils.isNotBlank(goodsNumbers)) {
			String[] goodsNumberArr = goodsNumbers.split(",");
			if (goodsNumberArr.length > 5) {
				throw new RuntimeException("商品数量超过5个");
			}
			// 删除当前资讯下的所有商品
			delArticleGoodsArchives(articleId);
			// 新增商品
			for (String goodsNumber : goodsNumberArr) {
				addArticleGoodsArchive(articleId, goodsNumber);
			}
		} else {
			// 删除当前资讯下的所有商品
			delArticleGoodsArchives(articleId);
		}
	}

	private void delArticleGoodsArchives(Integer articleId) {
		JfArticleGoodsArchives jfArticleGoodsArchives = new JfArticleGoodsArchives();
		jfArticleGoodsArchives.setUpdateTime(new Date());
		jfArticleGoodsArchives.setIsdel(true);
		JfArticleGoodsArchivesExample jfArticleGoodsArchivesExample = new JfArticleGoodsArchivesExample();
		jfArticleGoodsArchivesExample.createCriteria().andArticleIdEqualTo(articleId).andIsdelEqualTo(false);
		jfArticleGoodsArchivesMapper.updateByExampleSelective(jfArticleGoodsArchives, jfArticleGoodsArchivesExample);
	}

	@Override
	@Transactional
	public void putGoodsRegions(String uuid, String goodsNumbers, Integer range) {
		if (range == null) {
			range = 0;
		}

		// 判断uuid是否已存在
		SysOrgnization sysOrginzaition = regionService.getRegion(uuid);
		if (sysOrginzaition == null) {
			throw new RuntimeException("该地区不存在");
		}

		// 判断商品是否合法
		if (StringUtils.isBlank(goodsNumbers)) {
			throw new RuntimeException("商品编号为空");
		}

		// 投放商品
		String[] goodsNumberArray = goodsNumbers.split(",");
		for (String goodsNumber : goodsNumberArray) {
			putGoodsRegion(uuid, goodsNumber, range);
		}

	}

	private void putGoodsRegion(String uuid, String goodsNumber, Integer range) {
		JfGoodsArchives jfGoodsArchives = getJfGoodsArchives(goodsNumber);
		// 校验商品档案
		checkGoodsArchive(jfGoodsArchives, goodsNumber);

		// 锁住jf_put_area表
		updatePutArea(jfGoodsArchives.getId(), uuid);

		// 判断商品是否已投放到当前区域
		JfPutArea jfPutArea = getJfPutArea(jfGoodsArchives.getId(), uuid, range);
		if (jfPutArea != null) {
			throw new RuntimeException(String.format("编号为%s的商品投放重复", goodsNumber));
		}

		// 新增
		addJfPutArea(jfGoodsArchives.getId(), uuid, range);
	}

	private void addJfPutArea(Integer goodsArchivesId, String uuid, Integer range) {
		JfPutArea jfPutArea = new JfPutArea();
		jfPutArea.setAreaId(uuid);
		jfPutArea.setCreateTime(new Date());
		jfPutArea.setGoodsArchivesId(goodsArchivesId);
		jfPutArea.setPutRange(range.shortValue());
		jfPutAreaMapper.insert(jfPutArea);
	}

	private JfPutArea getJfPutArea(Integer goodsArchivesId, String uuid) {
		JfPutAreaExample jfPutAreaExample = new JfPutAreaExample();
		jfPutAreaExample.createCriteria().andAreaIdEqualTo(uuid).andGoodsArchivesIdEqualTo(goodsArchivesId);
		List<JfPutArea> jfPutAreaList = jfPutAreaMapper.selectByExample(jfPutAreaExample);
		if (CollectionUtils.isEmpty(jfPutAreaList)) {
			return null;
		} else {
			return jfPutAreaList.get(0);
		}
	}
	
	
	private JfPutArea getJfPutArea(Integer goodsArchivesId, String uuid, Integer range) {
		JfPutAreaExample jfPutAreaExample = new JfPutAreaExample();
		jfPutAreaExample.createCriteria().andAreaIdEqualTo(uuid).andGoodsArchivesIdEqualTo(goodsArchivesId).andPutRangeEqualTo(range.shortValue());
		List<JfPutArea> jfPutAreaList = jfPutAreaMapper.selectByExample(jfPutAreaExample);
		if (CollectionUtils.isEmpty(jfPutAreaList)) {
			return null;
		} else {
			return jfPutAreaList.get(0);
		}
	}
	

	private void updatePutArea(Integer goodsArchivesId, String uuid) {
		JfPutArea jfPutArea = new JfPutArea();
		jfPutArea.setCreateTime(new Date());
		JfPutAreaExample jfPutAreaExample = new JfPutAreaExample();
		jfPutAreaExample.createCriteria().andAreaIdEqualTo(uuid).andGoodsArchivesIdEqualTo(goodsArchivesId);
		jfPutAreaMapper.updateByExampleSelective(jfPutArea, jfPutAreaExample);
	}

	@Override
	public PageInfo<ExtPutGoods> pagePutGoods(int page, int size, String goodsName, String goodsNumber, String uuid,
			Integer range) {
		if (StringUtils.isBlank(uuid)) {
			return null;
		}
		PageHelper.startPage(page, size);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("goodsName", goodsName);
		map.put("goodsNumber", goodsNumber);
		map.put("uuid", uuid);
		map.put("range", range);
		return new PageInfo<ExtPutGoods>(sqlSessionTemplate.selectList("GoodsExtendSql.listPutGoods", map));
	}

	@Override
	@Transactional
	public void del(String putIds) {

		if (StringUtils.isBlank(putIds)) {
			throw new RuntimeException("投放id为空");
		}
		String[] putIdArray = putIds.split(",");
		for (String putId : putIdArray) {
			jfPutAreaMapper.deleteByPrimaryKey(Integer.parseInt(putId));
		}
	}

	@Override
	public List<JfGoodsArchives> getArticleGoodsArchives(Integer articleId) {
		return sqlSessionTemplate.selectList("GoodsExtendSql.listArticleGoods", articleId);
	}

}
